<template>
  <div class="home">
    <div class="dom" v-if="showPanel">
      <button @click="startDrawPolygon">开始绘制多边形</button>
      <button @click="startDrawLine">开始绘制线条</button>
      <button @click="stopDrawPolygon">停止绘制</button>
      <button @click="clearPolygon">清除绘制</button>
      <button @click="toggleEditMode" :class="{ active: isEditMode }">
        {{ isEditMode ? '退出编辑' : '编辑多边形' }}
      </button>
    </div>
    <div ref="mapCon" id="mapCon"></div>
  </div>
</template>

<script setup>
import "ol/ol.css";
import { ref, onMounted, onUnmounted, watch } from "vue";
import { Map, View, Feature } from "ol";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Fill } from "ol/style";
import Draw from "ol/interaction/Draw";
import { defaults } from "ol/interaction/defaults";
import XYZ from "ol/source/XYZ";
import { Modify, Select } from "ol/interaction";
import Polygon from "ol/geom/Polygon";
import LineString from "ol/geom/LineString";

// 定义props和emits
const props = defineProps({
    showPanel: {
        type: Boolean,
        default: true
    },
    area: {
        type: Array,
        default: [
            {   
                id: 1,
                polygon: [[[117.76539322860397,39.033600999852275],[117.72481595912116,39.02303400259113],[117.74468191397212,38.96850829672361],[117.77722826553645,38.990064971136356],[117.77596022586512,39.00570412708285],[117.76539322860397,39.033600999852275]]]
            },
            {
                id: 2,
                polygon: [[[117.7137435072634,39.10148664830954],[117.68997182368796,39.08765997379854],[117.7064386142226,39.05654879870957],[117.7343296067936,39.07032998430354],[117.7137435072634,39.10148664830954]]]
            }
        ]
    },
    line: {
        type: Array,
        default: () => [
            {
                id: 1,
                line: [[117.76539322860397,39.033600999852275],[117.72481595912116,39.02303400259113],[117.74468191397212,38.96850829672361]]
            },
            {
                id: 2,
                line: [[117.7137435072634,39.10148664830954],[117.68997182368796,39.08765997379854],[117.7064386142226,39.05654879870957]]
            }
        ]
    }
});

// 定义事件，用于向父组件发送编辑后的数据
const emit = defineEmits(['area-updated', 'line-updated']);

// 定义模板引用
const mapCon = ref(null);
const isEditMode = ref(false);

// 声明地图实例变量
let map;
let drawInteraction = null;
let vectorSource = null;
let vectorLayer = null;
let modifyInteraction = null;
let selectInteraction = null;
let selectedFeature = null;

// 初始化地图
const initMap = () => {
  console.log("初始化地图");

  // 1. 创建矢量数据源
  vectorSource = new VectorSource();

  // 2. 创建矢量图层（用于承载绘制的多边形和线条）
  vectorLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      fill: new Fill({ color: "rgba(255, 0, 0, 0.2)" }),
      stroke: new Stroke({ color: "#ff0000", width: 2 }),
    }),
  });

  // 3. 创建地图实例
  map = new Map({
    layers: [
      new TileLayer({
        title: "高德地图",
        source: new XYZ({
          url: "http://localhost:8081/amap-tiles/{z}/{x}/{y}/tile.png",
        }),
      }),
      vectorLayer,
    ],
    target: mapCon.value,
    view: new View({
      center: [117.74256851451989, 39.00380206757584],
      projection: "EPSG:4326",
      maxZoom: 21,
      minZoom: 10,
      zoom: 11.7,
    }),
    interactions: defaults(),
  });
  map.on("click",  (evt) => {
    const coordinate = evt.coordinate;
    
    console.log("点击位置的地理坐标:", coordinate); // 输出 [经度, 纬度] 格式的地理坐标数组
    console.log("点击位置的像素坐标:", evt.pixel); 
    // 获取地图视图
    const view = map.getView();
    // 获取中心点坐标
    const center = view.getCenter();
  });

  console.log("地图初始化完成", map);
  // 加载props中的多边形数据
  loadAreaPolygons();
  // 加载props中的线条数据
  loadLineData();
  
  // 添加键盘删除事件监听
  document.addEventListener('keydown', handleKeyDown);
};

// 加载props中的area多边形数据
const loadAreaPolygons = () => {
  console.log("加载多边形数据", props.area);
  if (!vectorSource || !props.area || props.area.length === 0) return;
  
  // 添加多边形
  props.area.forEach(item => {
    try {
      const polygon = new Polygon(item.polygon);
      const feature = new Feature({
        geometry: polygon,
        id: item.id,
        type: 'polygon'
      });
      // 设置样式
      feature.setStyle(new Style({
        fill: new Fill({ color: "rgba(0, 153, 255, 0.2)" }),
        stroke: new Stroke({ color: "#0099ff", width: 2 }),
      }));
      vectorSource.addFeature(feature);
    } catch (error) {
      console.error("添加多边形失败:", error);
    }
  });
};

// 加载props中的line线条数据
const loadLineData = () => {
  console.log("加载线条数据", props.line);
  if (!vectorSource || !props.line || props.line.length === 0) return;
  
  // 添加线条
  props.line.forEach(item => {
    try {
      const linestring = new LineString(item.line);
      const feature = new Feature({
        geometry: linestring,
        id: item.id,
        type: 'line'
      });
      // 设置样式
      feature.setStyle(new Style({
        stroke: new Stroke({ 
          color: "#ff6600", 
          width: 3,
          lineDash: [10, 5] // 虚线样式
        }),
      }));
      vectorSource.addFeature(feature);
    } catch (error) {
      console.error("添加线条失败:", error);
    }
  });
};

// 开始绘制多边形
const startDrawPolygon = () => {
  console.log("开始绘制多边形");
  
  // 如果在编辑模式，先退出
  if (isEditMode.value) {
    toggleEditMode();
  }

  // 先移除已存在的绘制交互
  stopDrawPolygon();

  try {
    // 创建绘制交互
    drawInteraction = new Draw({
      source: vectorSource,
      type: "Polygon",
      style: new Style({
        fill: new Fill({ color: "rgba(255, 0, 0, 0.1)" }),
        stroke: new Stroke({ color: "#ff0000", width: 2, lineDash: [5, 5] }),
      }),
    });

    // 添加到地图
    map.addInteraction(drawInteraction);
    console.log("绘制交互已添加", drawInteraction);

    // 监听绘制结束事件
    drawInteraction.on("drawend", (evt) => {
      console.log("绘制完成", evt);
      const coordinates = evt.feature.getGeometry().getCoordinates();
      console.log("多边形坐标:", coordinates);
      // 设置新绘制多边形的样式和类型
      evt.feature.setProperties({ type: 'polygon' });
      evt.feature.setStyle(new Style({
        fill: new Fill({ color: "rgba(0, 153, 255, 0.2)" }),
        stroke: new Stroke({ color: "#0099ff", width: 2 }),
      }));
    });

    // 监听绘制开始事件
    drawInteraction.on("drawstart", () => {
      console.log("开始绘制");
    });
  } catch (error) {
    console.error("创建绘制交互失败:", error);
  }
};

// 开始绘制线条
const startDrawLine = () => {
  console.log("开始绘制线条");
  
  // 如果在编辑模式，先退出
  if (isEditMode.value) {
    toggleEditMode();
  }

  // 先移除已存在的绘制交互
  stopDrawPolygon();

  try {
    // 创建绘制交互
    drawInteraction = new Draw({
      source: vectorSource,
      type: "LineString",
      style: new Style({
        stroke: new Stroke({ color: "#ff6600", width: 3, lineDash: [10, 5] }),
      }),
    });

    // 添加到地图
    map.addInteraction(drawInteraction);
    console.log("线条绘制交互已添加", drawInteraction);

    // 监听绘制结束事件
    drawInteraction.on("drawend", (evt) => {
      console.log("线条绘制完成", evt);
      const coordinates = evt.feature.getGeometry().getCoordinates();
      console.log("线条坐标:", coordinates);
      // 设置新绘制线条的样式和类型
      evt.feature.setProperties({ type: 'line' });
      evt.feature.setStyle(new Style({
        stroke: new Stroke({ 
          color: "#ff6600", 
          width: 3,
          lineDash: [10, 5] 
        }),
      }));
    });

    // 监听绘制开始事件
    drawInteraction.on("drawstart", () => {
      console.log("开始绘制线条");
    });
  } catch (error) {
    console.error("创建线条绘制交互失败:", error);
  }
};

// 停止绘制多边形
const stopDrawPolygon = () => {
  console.log("停止绘制");
  if (map && drawInteraction) {
    try {
      map.removeInteraction(drawInteraction);
      drawInteraction = null;
      console.log("绘制交互已移除");
    } catch (error) {
      console.error("移除绘制交互失败:", error);
    }
  }
};

// 清除绘制的多边形和线条
const clearPolygon = () => {
  console.log("清除绘制");
  if (vectorSource) {
    vectorSource.clear();
    console.log("矢量源已清空");
  }
  stopDrawPolygon();
  // 如果在编辑模式，退出
  if (isEditMode.value) {
    toggleEditMode();
  }
  // 重新加载原始数据
  loadAreaPolygons();
  loadLineData();
};

// 切换编辑模式
const toggleEditMode = () => {
  console.log("切换编辑模式", isEditMode.value ? "关闭" : "开启");
  
  // 先停止绘制
  stopDrawPolygon();
  
  if (isEditMode.value) {
    // 关闭编辑模式前，获取所有多边形和线条的最新数据
    const { updatedAreas, updatedLines } = getAllFeaturesData();
    
    // 通过事件发送更新后的数据给父组件
    emit('area-updated', updatedAreas);
    emit('line-updated', updatedLines);
    
    console.log("编辑后的多边形数据:", updatedAreas);
    console.log("编辑后的线条数据:", updatedLines);
    
    // 关闭编辑模式
    if (modifyInteraction) {
      map.removeInteraction(modifyInteraction);
      modifyInteraction = null;
    }
    if (selectInteraction) {
      map.removeInteraction(selectInteraction);
      selectInteraction = null;
    }
    selectedFeature = null;
  } else {
    // 开启编辑模式
    // 创建选择交互
    selectInteraction = new Select({
      style: (feature) => {
        const type = feature.get('type');
        if (type === 'line') {
          return new Style({
            stroke: new Stroke({ color: "#00ff00", width: 4 }),
          });
        } else {
          return new Style({
            fill: new Fill({ color: "rgba(255, 255, 0, 0.3)" }),
            stroke: new Stroke({ color: "#ffff00", width: 3 }),
          });
        }
      }
    });
    
    // 监听选择事件
    selectInteraction.on('select', (evt) => {
      if (evt.selected && evt.selected.length > 0) {
        selectedFeature = evt.selected[0];
        console.log("选中的要素:", selectedFeature.get('id'), "类型:", selectedFeature.get('type'));
      } else {
        selectedFeature = null;
      }
    });
    
    // 创建修改交互
    modifyInteraction = new Modify({
      features: selectInteraction.getFeatures()
    });
    
    // 添加交互到地图
    map.addInteraction(selectInteraction);
    map.addInteraction(modifyInteraction);
  }
  
  isEditMode.value = !isEditMode.value;
};

// 获取所有多边形和线条的最新数据
const getAllFeaturesData = () => {
  const features = vectorSource.getFeatures();
  const updatedAreas = [];
  const updatedLines = [];
  
  features.forEach((feature, index) => {
    const geometry = feature.getGeometry();
    const type = feature.get('type');
    const id = feature.get('id') || index + 1;
    
    if (geometry instanceof Polygon || type === 'polygon') {
      const coordinates = geometry.getCoordinates();
      updatedAreas.push({
        id: id,
        polygon: coordinates
      });
    } else if (geometry instanceof LineString || type === 'line') {
      const coordinates = geometry.getCoordinates();
      updatedLines.push({
        id: id,
        line: coordinates
      });
    }
  });
  
  return { updatedAreas, updatedLines };
};

// 处理键盘删除事件
const handleKeyDown = (e) => {
  if (isEditMode.value && selectedFeature && e.key === 'Delete') {
    console.log("删除选中的要素", selectedFeature.get('id'), "类型:", selectedFeature.get('type'));
    vectorSource.removeFeature(selectedFeature);
    selectedFeature = null;
  }
};

// 监听props变化
watch(() => props.area, (newArea) => {
  console.log("area props变化", newArea);
  // 清除所有要素，重新加载
  vectorSource.clear();
  loadAreaPolygons();
  loadLineData();
}, { deep: true });

// 监听line props变化
watch(() => props.line, (newLine) => {
  console.log("line props变化", newLine);
  // 清除所有要素，重新加载
  vectorSource.clear();
  loadAreaPolygons();
  loadLineData();
}, { deep: true });

// 挂载后初始化地图
onMounted(() => {
  console.log("组件挂载");
  // 确保DOM元素已渲染
  setTimeout(() => {
    initMap();
  }, 100);
});

// 卸载前清理
onUnmounted(() => {
  console.log("组件卸载，清理资源");
  stopDrawPolygon();
  if (modifyInteraction) {
    map.removeInteraction(modifyInteraction);
  }
  if (selectInteraction) {
    map.removeInteraction(selectInteraction);
  }
  if (map) {
    map.setTarget(null);
  }
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown);
});
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;
  position: relative;
  #mapCon {
    width: 100%;
    height: 100%;
  }
  .dom {
    position: absolute;
    z-index: 1000;
    left: 20px;
    top: 20px;
    background: white;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .dom button {
    margin: 0 5px;
    padding: 5px 10px;
    cursor: pointer;
    border: 1px solid #ddd;
    background: white;
    border-radius: 3px;
    transition: all 0.3s;
  }
  
  .dom button:hover {
    background: #f0f0f0;
  }
  
  .dom button.active {
    background: #0099ff;
    color: white;
    border-color: #0099ff;
  }
}
</style>